package main

import (
	"common"
	"encoding/json"
	"fmt"
	"github.com/fsnotify/fsnotify"
	"log"
	"net/http"
	"path"
	"sync"
)

const rootDir = "/var/www/html/"

var versions sync.Map

func setVersion(w http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	var version = req.Form.Get("version")
	var name = req.Form.Get("name")
	versions.Store(name, version)
	fmt.Println("set version ", name, version)
}

func getVersion(w http.ResponseWriter, req *http.Request) {
	req.ParseForm()

	var fileName = req.Form.Get("name")
	if len(fileName) == 0 {
		fileName = "enode" //兼容旧的协议
	}
	if fileName == "enode_amd64" {
		fileName = "enode"
	}
	//file := path.Join(rootDir, fileName)
	version := ""
	url := ""
	if v, ok := versions.Load(fileName); ok {
		if ver, ok := v.(string); ok {
			version = ver
			url = "http://101.37.33.124/" + fileName
			fmt.Println("get ", fileName, version)
		}
	}

	type Input struct {
		Version string
		Url     string
	}
	var input = Input{
		Version: version,
		Url:     url,
	}
	data, _ := json.Marshal(&input)
	w.Write(data)
}

func main() {
	var watcherFiles = make([]string, 0)
	var fileNames = []string{"enode"}
	for _, file := range fileNames {
		watcherFiles = append(watcherFiles, path.Join(rootDir, file))
	}

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()
	for _, file := range watcherFiles {
		version := common.GetENodeVersionFromFile(file)
		if len(version) > 0 {
			_, name := path.Split(file)
			versions.Store(name, version)
			fmt.Println("save ", name, version)
		}
	}

	go func() {
		for {
			select {
			case event := <-watcher.Events:
				log.Println("event:", event)
				if event.Op&fsnotify.Write == fsnotify.Write ||
					event.Op&fsnotify.Chmod == fsnotify.Chmod {
					log.Println("modified file:", event.Name)
					version := common.GetENodeVersionFromFile(event.Name)
					if len(version) > 0 {
						_, name := path.Split(event.Name)
						log.Println("update ", name, " version", version)
						versions.Store(name, version)
					}
				}

			case err := <-watcher.Errors:
				log.Println("error:", err)
			}
		}
	}()

	for _, file := range watcherFiles {
		err = watcher.Add(file)
		if err != nil {
			log.Println(err)
		}
	}

	http.HandleFunc("/version", getVersion)
	http.HandleFunc("/setversion", setVersion)
	err = http.ListenAndServe(":8090", nil)
	if err != nil {
		log.Println(err)
	}
}
